package com.showsu.editor.controller;


import com.showsu.editor.entity.po.TblUser;
import com.showsu.editor.entity.po.TblSysLog;
import com.showsu.editor.entity.vo.request.RequestVO;
import com.showsu.editor.enums.ResultCode;
import com.showsu.editor.service.IUserService;
import com.showsu.editor.service.ISysLogService;
import com.showsu.editor.session.ISession;
import com.showsu.editor.session.SessionException;
import com.showsu.editor.session.redis.RedisSessionManager;
import com.showsu.editor.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author eollse
 */
@Controller
public class BaseController {

    @Autowired
    private ISysLogService sysLogsService;

    @Autowired
    protected IUserService userService;

    @Autowired
    protected RedisSessionManager userSessionManager;

    /**
     * 获取会话id
     * @return
     */
    protected ISession getSession() {
        ISession session = userSessionManager.getSession(getRequest());
        if (session == null || session.getUserId() == null) {
            throw new SessionException(ResultCode.ALREADY_LOGOUT.getCode(), ResultCode.ALREADY_LOGOUT.getMessage());
        }
        return session;
    }

    /**
     * 获取会话id
     * @return
     */
    protected Long getUserId() {
        ISession session=this.getSession();
        return session.getUserId();
    }

    /**
     * 获取会话id
     * @return
     */
    protected TblUser getUser() {
        ISession session=this.getSession();
        return userService.getById(session.getUserId());
    }

    /**
     * 获取会话id
     * @return
     */
    protected TblUser getUser(Long userId) {
        return userService.getById(userId);
    }



    /**
     * 创建新的会话
     * @param userId
     * @return
     */
    protected ISession createSession(Long userId) {
        return userSessionManager.createSession(userId);
    }

    /**
     * 登出
     * @return sessionId
     */
    protected String deleteSession() {
        String sessionId = Constant.getSessionId(getRequest());
        userSessionManager.deleteSession(sessionId);
        return sessionId;
    }

    /**
     * 日志数据装配
     *
     * @param request
     * @param action
     * @param msg
     * @param userId
     * @param nickName
     * @return
     */
    public TblSysLog setLogs(HttpServletRequest request, String action, String msg, Long userId, String nickName) {
        String clientOrigin = "99";
        String ip = null;
        String os = null;
        String browser = null;
        if (request != null) {
            OsAndBrowserUtil osAndBrowser = OsAndBrowserUtil.getOSAndBrowser(request);
            String clintOriginKey = "CLIENT-ORIGIN";
            if (! StringUtil.isEmpty(request.getHeader(clintOriginKey))) {
                clientOrigin = request.getHeader(clintOriginKey);
            }
            ip = osAndBrowser.getIP();
            os = osAndBrowser.getOs();
            browser = osAndBrowser.getBrowser();
        }
        TblSysLog logs = new TblSysLog(action, msg, ip, os, browser, clientOrigin, userId, nickName);
        return logs;
    }

    public RequestVO getClientRequest(HttpServletRequest request) {
        RequestVO clientInfo = new RequestVO();
        String clientOrigin = "99";
        String ip = null;
        String os = null;
        String browser = null;
        if (request != null) {
            OsAndBrowserUtil osAndBrowser = OsAndBrowserUtil.getOSAndBrowser(request);
            String clintOriginKey = "CLIENT-ORIGIN";
            if (!StringUtil.isEmpty(request.getHeader(clintOriginKey))) {
                clientOrigin = request.getHeader(clintOriginKey);
            }
            ip = osAndBrowser.getIP();
            os = osAndBrowser.getOs();
            browser = osAndBrowser.getBrowser();
        }
        clientInfo.setClientIp(ip);
        clientInfo.setClientBrowser(browser);
        clientInfo.setClientOrigin(clientOrigin);
        clientInfo.setClientOs(os);
        return clientInfo;
    }

    public void saveLogs(TblSysLog logs) {
        sysLogsService.save(logs);
    }

    /**
     * 获取请求，避免参数传递
     * @return
     */
    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    }

    /**
     * 获取响应
     * @return
     */
    public HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();
    }

    /**
     * 获取请求，避免参数传递
     * @return
     */
    public RequestVO getClientRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        return getClientRequest(request);
    }

    public String getVersionCode() {
        return getRequest().getHeader(Constant.versionCode);
    }

    /**
     * 比较版本号
     * @return 如果返回负数 则表示 版本号小于线上版本
     *  如果返回0 则表示 版本号等于线上版本
     *  如果返回正数 则表示 版本号大于线上版本
     */
    public int compareSpecifiedVersionCode(String currentVersionCode) {
        return this.compareSpecifiedVersionCode(getVersionCode(),currentVersionCode);
    }

    /**
     * 比较版本号
     * @return 如果返回负数 则表示 版本号小于线上版本
     *  如果返回0 则表示 版本号等于线上版本
     *  如果返回正数 则表示 版本号大于线上版本
     */
    public int compareSpecifiedVersionCode(String versionCode,String currentVersionCode) {
        int compareResult=-1;
        //如果versionCode为空 ，则返回 版本号小于线上版本
        if(StringUtils.isBlank(versionCode)){
            return compareResult;
        }

        //如果versionCode长度大于线上版本号，则返回 版本号大于线上版本,得冗余版本给需要修改得渠道
        if(versionCode.length()>currentVersionCode.length()){
            compareResult=1;
        }else{
            compareResult=versionCode.compareToIgnoreCase(currentVersionCode);
        }
        return compareResult;
    }

    /**
     * 获取请求url域名地址
     * @param request
     * @return
     */
    protected String getSimpleDomain(HttpServletRequest request) {
        String domain = getDomain(request);
        if (domain.contains(Constant.datashowsDomainName)) {
            domain = Constant.datashowsDomainName;
        }
        return domain;
    }

    /**
     * 获取请求url地址
     * @param request
     * @return
     */
    protected String getDomain(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
    }

}